﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using WebChart;

namespace TSharp.Core.AppBox.Handlers
{
    public abstract class DynamicImageHandler : BaseHttpHandler
    {
        public DynamicImageHandler(HttpContext context, string requestType, string url, string pathTranslated)
            : base(context, requestType, url, pathTranslated)
        { }
        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public override void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            try
            {
                using (var bitmap = GetBitmap(context))
                    bitmap.Save(context.Response.OutputStream, ImageFormat.Png);
            }
            catch (Exception ex)
            {
                var engine = new WebChart.ChartEngine();
                {
                    using (var bitmap = engine.GenerateErrorBitmap(ex.ToString()))
                        bitmap.Save(context.Response.OutputStream, ImageFormat.Png);

                }
            }
            context.Response.Cache.SetNoStore();
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.ContentType = "image/png";
            context.Response.StatusCode = 200;
            context.Response.StatusDescription = "OK";
            context.ApplicationInstance.CompleteRequest();
        }

        protected abstract Bitmap GetBitmap(HttpContext context);

    }
}